using UnityEngine;
using System.Collections.Generic;
using Cinemachine;
using System.Collections;

// 玩家控制器1 单机 solider1
public class PlayerController : MonoBehaviour
{
    public float InputX;
    public float InputY;
    private Vector2 _speed = Vector2.zero;
    public float Speed = 5;
    private Vector3 _targetPostion = Vector3.zero;
    private Rigidbody rb;
    [Header("发射口位置")]
    public Transform[] GunPos;
    private float _shootColdTime;
    public float BulletFlySpeed;
    // 一个弹匣 20 发子弹
    private sbyte _magazine = 20;
    // 初始 3 个弹匣
    private sbyte _totalMagazine = 3;
    // 能装填弹夹
    private bool _canMagazine = true;
    // 动画
    public Animator anim;

    private void Awake()
    {
        transform.position = new Vector3(2.5f, 0, 2.5f);
        rb = GetComponent<Rigidbody>();
    }
    private void Start()
    {
        // 设置自由相机
        var freeCamera = FindObjectOfType<CinemachineFreeLook>();
        if (freeCamera != null)
        {
            freeCamera.Follow = transform;
            freeCamera.LookAt = transform;
        }
    }
    private void Update()
    {
        // 跟随鼠标旋转
        RotatePlayer();
        // 按键输入
        MoveInput();
        // 计算下一帧的位置
        BeforeMove();
        // 给刚体线速度来移动
        Move();

        // 射击冷却时间
        if (_shootColdTime > 0)
        {
            _shootColdTime -= Time.deltaTime;
        }

        // 左键发射子弹
        if (Input.GetMouseButtonDown(0) && _magazine > 0 && _shootColdTime <= 0)
        {
            anim.SetTrigger("shoot");
        }
        // 右键重新填装弹药
        if (Input.GetMouseButtonDown(1) && _totalMagazine > 0)
        {
            // 使用协程装弹药，延时 0.5 秒装好
            StartCoroutine(MagazineCor());
        }
    }
    // 装弹
    IEnumerator MagazineCor()
    {
        if (_canMagazine)
        {
            _canMagazine = false;
            yield return new WaitForSeconds(0.4f);
            _totalMagazine -= 1;
            _magazine = 20;
            _canMagazine = true;
        }
    }
    private void RotatePlayer()
    {
        // 法一 鼠标发射射线碰撞到地面时，才旋转
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo, 1000, 1 << 6))
        {
            Vector3 _dir = hitInfo.point;
            _dir.y = transform.position.y;
            transform.LookAt(_dir);
        }
        // 法二
        //获取鼠标的坐标，鼠标是屏幕坐标，Z轴为0，这里不做转换  
        // Vector3 mouse = Input.mousePosition;
        //获取物体坐标，物体坐标是世界坐标，将其转换成屏幕坐标
        // Vector3 obj = Camera.main.WorldToScreenPoint(transform.position);
        //屏幕坐标向量相减，得到指向鼠标点的目标向量
        // Vector3 direction = new Vector3(mouse.x - obj.x, 0, mouse.y - obj.y).normalized;
        // 改变玩家模型的方向
        // transform.GetChild(0).rotation = Quaternion.LookRotation(direction);
        // 或改变当前控制器的方向
        // transform.rotation = Quaternion.LookRotation(direction);
    }
    private void MoveInput()
    {
        InputX = Input.GetAxisRaw("Horizontal");
        InputY = Input.GetAxisRaw("Vertical");
    }
    private void BeforeMove()
    {
        _speed.x = InputX * Speed;
        _speed.y = InputY * Speed;

        _targetPostion.x = _speed.x * Time.deltaTime;
        _targetPostion.z = _speed.y * Time.deltaTime;

    }
    private void Move()
    {
        // 不跟随当前物体，以世界坐标的前后左右来移动
        // rb.velocity = _targetPostion * 100;

        // 跟随当前物体的前后左右移动
        rb.velocity = transform.TransformVector(_targetPostion) * 100;

        if (rb.velocity.x != 0 || rb.velocity.z != 0)
        {
            anim.SetBool("running", true);
        }
        else
        {
            anim.SetBool("running", false);
        }
    }
    // animation event
    public void Shoot()
    {
        // 消耗 1 子弹
        _magazine -= 1;
        // 默认射速 1 秒 1 发子弹
        _shootColdTime = 1;
        // 从对象池取出一个子弹
        GameObject b = BulletPool.Instance.GetBullet();

        // 法1 直接设置世界坐标    + GunPos[0].up 确保子弹在枪管尾部一定距离时飞出，而不是与枪管发生碰撞
        b.transform.SetPositionAndRotation(GunPos[0].position, Quaternion.Euler(new Vector3(90, 0, -transform.eulerAngles.y)));

        // 法2 从物体中心开始计算子弹位置
        // b.transform.Translate(transform.position, Space.World);
        // b.transform.eulerAngles = new Vector3(90, 0, -transform.eulerAngles.y);
        // b.transform.Translate(Vector3.up * 2f, Space.Self);

        // 法3 从发射口开始计算子弹位置
        // b.transform.Translate(GunPos[0].position, Space.World);
        // b.transform.eulerAngles = new Vector3(90, 0, -transform.eulerAngles.y);
        // b.transform.Translate(Vector3.up, Space.Self);

        // 给子弹初速度
        b.GetComponent<Bullet>().Rb.velocity = b.transform.TransformVector(Vector3.up) * BulletFlySpeed;
    }
}
